import yaml
from typing import Dict, Any, Optional


class ConfigLoader:
    """配置加载器，支持嵌套配置访问和自动创建路径"""

    def __init__(self, config_path: str):
        self.config_path = config_path
        self.config = self._load_config()

    def _load_config(self) -> Dict[str, Any]:
        """加载并解析YAML配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except Exception as e:
            raise RuntimeError(f"配置文件加载失败: {str(e)}")

    def get(self, key: str, default: Optional[Any] = None) -> Any:
        """通过点符号路径获取配置值，如'data.split.test_ratio'"""
        keys = key.split('.')
        current = self.config

        for k in keys:
            if isinstance(current, dict) and k in current:
                current = current[k]
            else:
                return default
        return current

    def set(self, key: str, value: Any) -> None:
        """设置配置值"""
        keys = key.split('.')
        current = self.config

        for k in keys[:-1]:
            if k not in current:
                current[k] = {}
            current = current[k]

        current[keys[-1]] = value